const Router = require('@koa/router')
const mongoose = require('mongoose')
const Customer = mongoose.model('Customer')

const router = new Router({
    prefix: '/customer',
})
/*更新和添加接口 */
router.post('/updateandadd', async (ctx) => {
    let {
        _id,
        cusName,//客户名
        legalPerson,//法人
        province,//省份
        cusType,//客户类型   0潜在客户 1有意向者 2真正客户 3历史客户
        satisfaction,//满意度 1-5星
        credit,//信用度  1-5星
        cusAddress,//地址
        cusPhone,//电话
        cusWebsite,//网站
        cusFund,//注册资金
        cusLicence,//营业执照
    } = ctx.request.body
    const one = await Customer.findOne({
        _id: _id
    })
    if (one) {
        //存在更新
        one.cusName = cusName
        one.legalPerson = legalPerson
        one.province = province
        one.cusType = cusType
        one.satisfaction = satisfaction
        one.credit = credit
        one.cusAddress = cusAddress
        one.cusPhone = cusPhone
        one.cusWebsite = cusWebsite
        one.cusFund = cusFund
        one.cusLicence = cusLicence
        const res = await one.save()//更新
        ctx.body = {
            data: res,
            msg: "更新成功",
            code: 200
        }
    } else {
        //不存在 添加
        if (cusName == "" || legalPerson == "" || province == "" || cusType == "") {
            ctx.body = {
                data: null,
                code: 0,
                msg: '以上必填',
            }
            return
        }
        const customer = new Customer({
            cusName,
            legalPerson,
            province,
            cusType,
            satisfaction,
            credit,
            cusAddress,
            cusPhone,
            cusWebsite,
            cusFund,
            cusLicence,
        })
        const res = await customer.save()
        ctx.body = {
            data: res,
            code: 200,
            msg: '添加客户信息成功'
        }
    }
})


//删除操作
router.delete('/:id', async (ctx) => {
    const {
        id
    } = ctx.params
    const delMsg = await Customer.deleteOne({
        _id: id
    })
    ctx.body = {
        data: delMsg,
        code: 200,
        msg: '删除成功'
    }
})



//获取列表
router.get('/list', async (ctx) => {
    let {
        page,
        size,
        keyword
    } = ctx.query

    page = Number(page)
    size = Number(size)

    let reg = new RegExp(keyword, "gim")  //模糊查询
    const list = await Customer
        .find({ "cusName": { $regex: reg } })
        .sort({ _id: -1 }) //-1倒序
        .skip((page - 1) * size)
        .limit(size)
        .exec()

    const total = await Customer.countDocuments().exec()
    ctx.body = {
        msg: '获取客户列表成功',
        data: {
            list,
            page,
            size,
            total
        },
        code: 200
    }
})

module.exports = router